package com.mk.web.threadpool.producer;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by WangChen on 2019/1/8 11:59.
 */
public class ProducerConsumerTest {

    public static void main(String [] args){
    ArrayBlockingQueue<Integer> blockingQueue = new ArrayBlockingQueue<>(100);
//        P p = new P(blockingQueue);
        /*new Thread(new Runnable() {
            @Override
            public void run() {
                new P(blockingQueue).produce();
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                new C(blockingQueue).consume();
            }
        }).start();*/

        ExecutorService producerPool = Executors.newFixedThreadPool(10);
        producerPool.execute(new P(blockingQueue));
        producerPool.execute(new P(blockingQueue));
        producerPool.execute(new P(blockingQueue));
        producerPool.execute(new P(blockingQueue));

        ExecutorService consumerPool = Executors.newFixedThreadPool(10);
        consumerPool.execute(new C(blockingQueue));
        consumerPool.execute(new C(blockingQueue));
        consumerPool.execute(new C(blockingQueue));
        consumerPool.execute(new C(blockingQueue));
    }
}
class P implements Runnable{
    private ArrayBlockingQueue<Integer> blockingQueue;
    P(ArrayBlockingQueue<Integer> blockingQueue){
        this.blockingQueue = blockingQueue;
    }
    void produce(){
        try {
            int i = (int)(Math.random() * 1000);
            while (true){
                blockingQueue.put(i);
                System.out.println(blockingQueue.size()+ " : " + i);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        produce();
    }
}
class C implements Runnable{
    private ArrayBlockingQueue<Integer> blockingQueue;
    C(ArrayBlockingQueue<Integer> blockingQueue){
        this.blockingQueue = blockingQueue;
    }
    void consume(){
        try {
            while (true){
                blockingQueue.take();
                System.out.println(blockingQueue.size());
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        consume();
    }
}
